//
//  PostalTrackerAppDelegate.m
//  PostalTracker
//
//  Created by Aleksandr Batsuev on 1/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PostalTrackerAppDelegate.h"
#import "USPSTrackInfo.h"
#import "PostalTrackerSystemMenuItemView.h"
#import "ContentWindow.h"
#import <Growl/GrowlApplicationBridge.h>

#define STATUS_UPDATE @"Status update"

@implementation PostalTrackerAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
}

-(void)dealloc
{
    [menuletMainItem release];
	[super dealloc];
}

- (void)hideContentWindow
{
	[contentWindow orderOut:self];
}

- (void)awakeFromNib
{
	lastStatus = [[NSString alloc] init];
	
	trackInfo = [[USPSTrackInfo alloc] init];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTrackingInfoLoaded:) name:@"trackingInfoLoaded" object:trackInfo];
	
	float width = 30.0;
    float height = [[NSStatusBar systemStatusBar] thickness];
    NSRect viewFrame = NSMakeRect(0, 0, width, height);
	
	menuletMainItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:width] retain];
	
	menuView = [[PostalTrackerSystemMenuItemView alloc] initWithFrame:viewFrame];
	[menuView setController:self];
	[menuletMainItem setView:menuView];
	
	contentWindow = [[ContentWindow alloc] initWithView:contentView attachedToPoint:NSMakePoint(0, 0)];
	[contentWindow makeKeyAndOrderFront:self];
	[contentWindow setDelegate:self];
	[contentWindow setInitialFirstResponder:contentView];	
	[self hideContentWindow];
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *lastTrackingNumber = [defaults objectForKey:@"lastTrackingNumber"];
	if (lastTrackingNumber != nil) {
		[searchField setStringValue:lastTrackingNumber];
		[self findInfo:nil];
	}
	
	[resultsField setController:self];
	[updateButton setEnabled:NO];
	[detailsButton setEnabled:NO];
	[detailsButtonEx setEnabled:NO];
	
	[GrowlApplicationBridge setGrowlDelegate:self];
}

NSPoint windowPoint;

- (void)showContentWindow:(NSPoint)pt
{
	windowPoint = pt;
	
	[contentWindow makeKeyAndOrderFront:self];
	[contentWindow setFrameOrigin:NSMakePoint(pt.x - 15, pt.y-[contentView frame].size.height)];
	
	[menuView showNoNews];
}

- (void)toggleAttachedWindowAtPoint:(NSPoint)pt
{
	if ([contentWindow isVisible])
		[self hideContentWindow];
	else
		[self showContentWindow:pt];
}

- (void)showResult:(NSString*)result
{
	[resultsField setStringValue:result];
	[updateButton setEnabled:YES];
}

- (void)checkResult:(NSString*)result
{
	if ([result isEqualToString:@"No information found"]) return;
	
	if (![lastStatus isEqualTo:result]) {
		if (![contentWindow isVisible]) {
			[GrowlApplicationBridge notifyWithTitle:[searchField stringValue] description:result notificationName:STATUS_UPDATE iconData:nil priority:0 isSticky:NO clickContext:[searchField stringValue]];
			[menuView showUpdated];
		}
	}
	lastStatus = [NSString stringWithFormat:@"%@", result];
}	

- (void)handleTrackingInfoLoaded:(NSNotification*)note {
	[self showResult:[trackInfo stringResult]];
	[self checkResult:[trackInfo stringResult]];
}

- (void)checkTimer
{
	if (updateTimer != nil) {
		[updateTimer invalidate];
		updateTimer = nil;
	}
	
	NSString *request = [searchField stringValue];

	if (request != nil && ![request isEqual:@""]) {
		updateTimer = [NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(updateInfoFromTimer) userInfo:nil repeats:YES];
	}
}

-(IBAction) findInfo:(id)sender
{
	[self updateInfoFromTimer];
	
	[self checkTimer];
}

- (void)updateInfoFromTimer
{
	NSString *request = [searchField stringValue];
	if (request == nil || [request isEqual:@""]) {
		[self showResult:@""];
	}else {
		[self showResult:@"Loading..."];
		[trackInfo getInfo:[searchField stringValue]];
		
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject:[searchField stringValue] forKey:@"lastTrackingNumber"];
		
		[updateButton setEnabled:NO];
		[detailsButton setEnabled:YES];
		[detailsButtonEx setEnabled:YES];
	}
	
	NSLog(@"Timer");
}

- (IBAction)showAbout:(id)sender
{
	[NSApp orderFrontStandardAboutPanel:sender];
}


- (void)windowDidResignKey:(NSNotification *)notification
{
	[(PostalTrackerSystemMenuItemView*)[menuletMainItem view] hideContent];
	[self hideContentWindow];
}

- (IBAction)showDetailedInfo:(id)sender
{
	NSString *trackingId = [searchField stringValue];
	if (trackingId == nil || [trackingId isEqual:@""]) return;
	
	[(PostalTrackerSystemMenuItemView*)[menuletMainItem view] hideContent];
	[self hideContentWindow];
	
	NSString *fileContent = [NSString stringWithFormat:@"<html><head><body onload='document.getElementById(\"frm\").submit();'><form id='frm' method='POST' action='http://trkcnfrm1.smi.usps.com/PTSInternetWeb/InterLabelInquiry.do'><input type='hidden' name='origTrackNum' value='%@' /></form></body></head></html>",trackingId];
	
	NSString* htmlPath = [NSString stringWithFormat:@"%@/Contents/Resources/usps.html", [[NSBundle mainBundle] bundlePath]];

	[fileContent writeToFile:htmlPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
	[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:htmlPath]];
}

- (IBAction)updateInfo:(id)sender
{
	[self findInfo:nil];
}

//GROWL
- (NSDictionary *) registrationDictionaryForGrowl
{
	return [NSDictionary dictionaryWithObjectsAndKeys:
							   [NSArray arrayWithObject:STATUS_UPDATE],GROWL_NOTIFICATIONS_ALL,
							   [NSArray arrayWithObject:STATUS_UPDATE],GROWL_NOTIFICATIONS_DEFAULT, nil];
}

- (NSString *) applicationNameForGrowl
{
	return @"USPS tracker";
}

- (void) growlNotificationWasClicked:(id)clickContext
{
	[menuView showNoNews];
	[self showDetailedInfo:nil];
}

- (BOOL)contentWindowVisible { 
	return [contentWindow isVisible];
}

@end
